package cn.edu.tsinghua.weibo.servlet;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.edu.tsinghua.weibo.util.DB;
import cn.edu.tsinghua.weibo.util.MD5;

@SuppressWarnings("serial")
public class Register extends HttpServlet {

	private final static String SQL = "insert into user(email, password, nick, sex, location) values(?, ?, ?, ?, ?)";
	
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		HttpSession session = request.getSession();
		String validcode_expected = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		String validcode = request.getParameter("validcode");

		if (!validcode.equalsIgnoreCase(validcode_expected)) {
			request.setAttribute("message", "vaild code is not correct.");
			request.getRequestDispatcher("signup.jsp").forward(request, response);
		} else {
			String email = request.getParameter("email");
			String password = MD5.encrypt(request.getParameter("password"));
			String nick = request.getParameter("nick");
			String sex = request.getParameter("sex");
			String location = request.getParameter("location");


			try {
				Connection connection = DB.getConnection();
				PreparedStatement preparedStatement = connection.prepareStatement(SQL);
				preparedStatement.setString(1, email);
				preparedStatement.setString(2, password);
				preparedStatement.setString(3, nick);
				preparedStatement.setInt(4, Integer.parseInt(sex));
				preparedStatement.setInt(5, Integer.parseInt(location));

				preparedStatement.executeUpdate();
				DB.close(preparedStatement, connection);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			response.sendRedirect("index.jsp");
		}
	}

}
